<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<view class="my_navbar" :style="{ height: myTopHeight + 'px' }">
			<view 
				class="account_book_name" 
				:style="{ marginTop: topF + 'px', height: capsuleHeight + 'px', 
				lineHeight: capsuleHeight + 'px' }"
				@click="showDrawerHandle"
				>
				<view class="account_book_name_value">
					{{ selectedAccountBookName }}
				</view>
				<view class="account_book_name_icon">
					<image src="../../static/index/index_right.png" mode="heightFix"></image>
				</view>
			</view>
		</view>
		<!-- 当月收支数据 -->
		<view class="month_IE_data" :style="{marginTop: myTopHeight + 'px'}">
			<view class="month_IE_datamonth_info">
				{{ getFormattedDate() }} · 支出
			</view>
			<view class="month_IE_data_expend">
				￥<span class="month_IE_data_expend_value">{{ monthDataOfAccountBook.expenditure }}</span>
			</view>
			<view class="month_IE_data_income_and_balance">
				收入￥{{ monthDataOfAccountBook.income }} &nbsp 结余￥{{ monthDataOfAccountBook.balance }}
			</view>
		</view>
		<!-- 账单列表 -->
		<view class="bill_box">
			<view class="bill_box_top">
				<view class="bill_box_top_title">
					近7天账单
				</view>
				<view class="bill_box_top_goto" @click="gotoAllPage">
					<view class="bill_box_top_goto_text">
						全部账单
					</view>
					<view class="bill_box_top_goto_img">
						<image src="../../static/index/index_right.png" mode="heightFix"></image>
					</view>
				</view>
			</view>
			<!-- 账单组件 -->
			<Bill ref="billComponentRef" showPosition="index" :billFilterVo="billFilterVo"></Bill>
		</view>
		<!-- 左侧抽屉 -->
		<uni-drawer ref="showDrawer" mode="left" :mask-click="true">
			<!-- 账本管理 -->
			<view class="account_book_manage_btn" 
				:style="{marginTop: navHeightRef + (capsuleHeight/2) + 'px'}"
				@click="gotoAccountBookPage"
				>
				<view class="account_book_manage_btn_text">
					账本管理
				</view>
				<view class="account_book_manage_btn_icon">
					<image src="../../static/common/right.png" mode="heightFix"></image>
				</view>
			</view>
			<!-- 账本展示 -->
			<view class="books">
				<view class="book_item" 
					v-for="(item, index) of accountBookData" 
					:key="index"
					@click="switchBook(item)"
					>
					<view class="book_item_book">
						<!-- 默认标识 -->
						<view class="default_text" v-if="isSelectBook(item)">
							在选
						</view>
						<image src="../../static/index/book_back.png" mode="heightFix"></image>
					</view>
					<view class="book_item_text" :class="{'default_book_text': isSelectBook(item)}">
						{{ item.name }}
					</view>
				</view>
			</view>
		</uni-drawer>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Bill from "../../components/Bill/Bill.vue";
import { onShow } from "@dcloudio/uni-app";

// 账单组件ref
const billComponentRef = ref(null)

// 账本月数据统计数据
let monthDataOfAccountBook = ref({});

// 账本数据
let accountBookData = ref([]);
// 选择的账本名称
let selectedAccountBookName = ref('欢迎使用');
// 用户信息
let userInfo = ref({});

// 自定义导航栏的参数
let myTopHeight = ref(10); // 导航栏加状态栏的高度
let topF = ref(0); // 胶囊按钮距离状态栏底部的高度
let capsuleHeight = ref(0); // 胶囊按钮高度
let navHeightRef = ref(0);

// 左侧抽屉参数
let showDrawer = ref();

// 获取首页账单组件的参数
let billFilterVo = ref({accountBookId: ""});

onMounted(() => {
	getUserAllAccountBook(); // 获取账本数据
	dynamicComputeNavbarHeight(); // 动态获取状态栏
	getMonthDataOfBook(); // 获取账本月统计数据
});

onShow(async()=>{
	getMonthDataOfBook();
	// ?作用：当 value 为 null 或 undefined 时，阻止继续访问后面的属性/方法
	billComponentRef.value?.updateBillData();
})

// 展开左侧抽屉
function showDrawerHandle(){
	showDrawer.value.open();
}


// 切换账本
function switchBook(book){
	// 更换已选账本状态 和 本地存储中已选择账本的名称
	selectedAccountBookName.value = book.name;
	uni.setStorageSync("selectedBook", book.name);
	
	// 切换后关闭抽屉
	showDrawer.value.close();
	
	// 过滤展示选择的账本中的账单
	getMonthDataOfBook();
}

// 获取账本月统计数据
async function getMonthDataOfBook(){
	
	// 获取当前选择的账本ID
	let accountBookId = getBookIdByBookName();
	
	// 赋值账本ID，用于过滤首页显示的账单
	billFilterVo.value.accountBookId = accountBookId;
	
	let yearMonth = getFormattedDate();
	
	const res = await uni.$http.get(`/accountBooks/getMonthDataOfAccountBook/${yearMonth}/${accountBookId}`);
	if(res.data.code ==0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	monthDataOfAccountBook.value = res.data.data;
}

// 获取当前年月
function getFormattedDate() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // +1 因为月份从0开始
  return `${year}-${month}`;
}

// 根据账本名称获取账本ID
function getBookIdByBookName(){
	// 获取当前已经选择的账本名称
	let bookName = uni.getStorageSync("selectedBook");
	for (let book of uni.getStorageSync('accountBookData')) {
		if(bookName == book.name){
			return book.id;
		}
	}
	return 0;
}


// 跳转账本管理页面
function gotoAccountBookPage(){
	uni.navigateTo({
		url:"/subPkg1/account_book/account_book"
	})
}

// 判断是否为已选函数
function isSelectBook(book){
	return uni.getStorageSync("selectedBook") == book.name;
}

// 获取用户所有的账本数据
async function getUserAllAccountBook() {
	if (uni.getStorageSync('userInfo') == '') {
		// 没有找到用户登录信息，跳转到登录页
		uni.$showT('请先登录，即将跳转...');
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/my/my'
			});
		}, 1500);
		return 1;
	}
	// 获取openId
	userInfo.value = JSON.parse(uni.getStorageSync('userInfo'));

	const res = await uni.$http.get(`/accountBooks/getAllByOpenId?openId=${userInfo.value.openid}`);

	// 遍历找出默认账本，将默认账本设置为“选择的账本”
	for (let item of res.data.data) {
		if (item.isDefault == 1) {
			console.log('找到默认账本==>', item.name);
			selectedAccountBookName.value = item.name;
			// 存储到localstorage - 状态共享
			uni.setStorageSync('selectedBook', item.name);
		}
	}

	accountBookData.value = res.data.data; // 存储账本数据
	uni.setStorageSync('accountBookData', accountBookData.value);
}

// 动态计算状态栏高度
function dynamicComputeNavbarHeight() {
	let stateHeight = 0; //  接收状态栏高度
	let navHeight = wx.getMenuButtonBoundingClientRect().height; //  获取胶囊高度
	capsuleHeight.value = navHeight;
	let top = 0; // 状态栏顶部到胶囊顶部的高度
	wx.getSystemInfo({
		success(res) {
			navHeightRef.value = res.statusBarHeight; 
			stateHeight = res.statusBarHeight; // 状态栏的高度
		}
	});
	//状态栏顶部到胶囊顶部的高度 - 状态栏的高度 = 胶囊按钮顶部到状态栏底部的高度
	top = wx.getMenuButtonBoundingClientRect().top - stateHeight;
	//  最终可以计算出，顶部导航栏的高度
	navHeight = navHeight + top * 2;
	topF.value = top + stateHeight;

	myTopHeight.value = navHeight + stateHeight;
}

// 跳转账单过滤页面 - 全部账单
function gotoAllPage(){
	uni.navigateTo({
		url:"/subPkg2/filter_bill/filter_bill"
	})
}

// 后置处理器
async function afterHandle(){
	// 刷新数据
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	const res = await uni.$http.get(`/accountBooks/getAllByOpenId?openId=${userInfo.openid}`);
	
	accountBookData.value = res.data.data;
	uni.setStorageSync("accountBookData", accountBookData.value); 
}
</script>

<style scoped>
.my_navbar {
	position: fixed;
	top: 0px;
	width: 100vw;
}

.account_book_name {
	padding-left: 10px;
	font-weight: 600;
	display: flex;
	align-items: center;
	/* border: solid red 1px; */
	position: relative;
}

.account_book_name_icon {
	height: 100%;
}

.account_book_name_icon image {
	height: 17px;
	position: relative;
	top: 3px;
	left: 2px;
}

.books{
	display: flex;
	position: relative;
	justify-content: space-around;
	margin-top: 5px;
}

.book_item{
	width: 40%;
	/* border: solid red 1px; */
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	font-size: 13px;
	color: #4c4c4c;
}

.book_item_book{
	height: 90px;
	width: 85%;
	border-radius: 10rpx;
	z-index: -1;
	overflow: hidden;
	position: relative;
}

.default_text{
	position: absolute;
	background-color: #2a9fbf;
	color: white;
	border-radius: 5px;
	padding: 2px 5px;
}

.book_item_book image{
	height: 100%;
}

.book_item_text{
	padding-top: 10rpx;
}

.default_book_text{
	color: #2a9fbf;
}

.account_book_manage_btn{
	font-size: 13px;
	color: #7c7c7c;
	display: flex;
	align-items: center;
	position: relative;
	left: 20px;
}

.account_book_manage_btn_icon image{
	height: 25px;
	position: relative;
	top: 2px;
	right: 4px;
}

.month_IE_data{
	box-sizing: border-box;
	width: 97vw;
	margin: 0 auto;
	border: solid #dddddd 1px;
	border-radius: 15rpx;
	padding: 20rpx;
	position: relative;
	top: 10px;
	font-size: 14px;
	background: linear-gradient(to bottom right, #f2eff6, #f2edf5, #e2eff7, #e5e0f4, #f4f2f8);
}

.month_IE_data_expend{
	padding: 20rpx 0px;
	font-size: 17px;
}

.month_IE_data_expend_value{
	font-size: 25px;
}



/* =====账单列表样式开始==== */

.bill_box{
	border-radius: 15rpx;
	position: relative;
	top: 20px;
	box-sizing: border-box;
	width: 97vw;
	margin: 0 auto;
	/* border: solid #000 1px; */
	padding: 20rpx;
	background-color: #fff;
}

.bill_box_top{
	display: flex;
	justify-content: space-between;
	padding: 15rpx 10rpx;
	padding-bottom: 30rpx;
	/* border: solid red 1px; */
	align-items: center;
}

.bill_box_top_goto{
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	/* left: 5px; */
}

.bill_box_top_goto image{
	height: 12px;
	position: relative;
	top: 1px;
}

.bill_box_top_title{
	font-weight: 600;
	font-size: 15px;
}

.bill_box_top_goto{
	font-size: 13px;
	color: #5e5e5e;
}
</style>
